package org.next.tesigiulia.utils;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.*;

import java.io.IOException;
import java.util.logging.Logger;

/**
 * Created with IntelliJ IDEA.
 * User: gianluca
 * Date: 11/03/13
 * Time: 16.42
 * To change this template use File | Settings | File Templates.
 */
public class MarineScraper {
    private final WebClient webClient;
    private static final long MILLISECONDS = 20000;
    private static final int MAX_NUM_PAGES = 10;
    private String pageUrl = "http://www.marinetraffic.com/ais/it/datasheet.aspx?datasource=SHIPS_CURRENT&alpha=A&level0=200&var_page=";
    private MyVesselsList vesselsList = new MyVesselsList();
    private Thread thread;
    private Runnable runnable;
    private int num;

    public MarineScraper(WebClient webClient, int numberOfRefresh) {
        this.webClient = webClient;
        this.num = numberOfRefresh;
        webClient.setJavaScriptEnabled(false);

        runnable = new Runnable() {
            @Override
            public void run() {
                while (--num >= 0) {
                    Logger.getAnonymousLogger().info("Rimanenti " + num);
                    vesselsList.getList().clear();
                    for (int i = 1; i < MAX_NUM_PAGES; i++) {
                        try {
                            scrapePage(i);
                        } catch (IOException e) {
                            Logger.getAnonymousLogger().warning(e.toString());
                        }
                    }
                    MyEventBus.getInstance().getEventBus().post(vesselsList);
                    try {
                        Thread.sleep(MILLISECONDS);
                    } catch (InterruptedException e) {
                        Logger.getAnonymousLogger().warning(e.toString());
                    }
                }
            }
        };
        thread = new Thread(runnable);
    }

    private void scrapePage(int pageNumber) throws IOException {
        HtmlPage page = webClient.getPage(pageUrl + pageNumber);
        DomNodeList<DomElement> elements = page.getElementsByTagName("table");
        HtmlTable htmlTable = (HtmlTable) elements.get(0);
        for (int i = 3; i < htmlTable.getRowCount(); i++) {
            HtmlTableRow row = htmlTable.getRow(i);
            String name = row.getCell(1).asText();
            String angle = row.getCell(4).asText();
            String mmsiRaw = row.getCell(0).getElementsByTagName("a").get(0).getAttribute("href");
            String mmsi = mmsiRaw.split("&")[1].split("=")[1];
            String lat = mmsiRaw.split("&")[3].split("=")[1];
            String lon = mmsiRaw.split("&")[2].split("=")[1];
            //Logger.getAnonymousLogger().info("Vessel Name: "+name+ " "+mmsi +" " + lat + " "+lon);

            Vessel vessel = new Vessel();
            vessel.setName(name);
            vessel.setMmsi(mmsi);
            vessel.setLat(Double.parseDouble(lat));
            vessel.setLon(Double.parseDouble(lon));
            vessel.setAngle(Double.parseDouble(angle));

            vesselsList.getList().add(vessel);
        }
    }

    public void start() throws IOException {
        thread.start();
        Logger.getAnonymousLogger().info("");

    }
}
